import React,{PropTyeps} from "react";
import Relay from 'react-relay';
import {message,DatePicker} from 'antd';
import {type} from 'fly';
import moment from 'moment';


import Header from '../components/View_Header';
import BarNavUiComponent from '../components/Logic_barNavUi';
import Logic_chartVertical from '../components/Logic_chartVertical';
import Logic_chartYaxis from '../components/Logic_chartYaxis'
import Logic_chartTransverse from '../components/Logic_chartTransverse';
import View_describe from '../components/View_IllustrDescribe';

import {dateFormat,scrollMove} from "../utils";

import ShowWorkGroupProInfoMutation from '../mutaion/ShowWorkGroupProInfoMutation';

import "./style.scss";

export default class FactoryresourceDetailsSewing extends React.Component {

    static defaultProps = {};

    constructor(props) {
        super(props);

        let date = new Date();

        let preDate = this.preDate = moment(new Date().setDate(date.getDate() - 45));  //第一次默认选择的时间

        this.state = {
            date:preDate,   //选择的时间
            currentDate:null,   //选择之后计算出的最后时间
            dateArr:[],  // 时间数据数组
            data:null,  // 竖向图标的数据
            transverseData:[],  //横向图标的数据
            stylePlanData:{},   //横向图标数据bar
            yAxis:[], // Y轴刻度
            canvasWidth:3720,  //两个元素的宽度
            proWorkGroup:{}   //班组数据
        };
        this.MAX_TOTAL_COUNT = 0;  //默认值
    }

    httpRequest = ({startDate,endDate},callback)=>{
        Relay.Store.commitUpdate(
            new ShowWorkGroupProInfoMutation({
                enterpriseId:sessionStorage.getItem("enterpriseId"),
                workGroupId:this.propState.workGroupId,  //班组id
                workShopId:this.propState.workShopId,  // 车间id
                startDate:startDate,
                endDate:endDate
            }),
            {
                onFailure: () => {
                    message.error('请求失败');
                },
                onSuccess: (response) => {
                    let content = response.showWorkGroupProInfo.showWorkGroupProInfo;

                    this.setState({proWorkGroup:content.proWorkGroup});

                    if(content.errorCode == 0){
                        callback && callback(content);
                    }
                }
            }
        );
    };

    //整理时间data格式 [转JSON] [设置画布宽度]
    reDataformat = (data)=>{
        let censusData = JSON.parse(data.censusGoodsReports);
        let styleData = JSON.parse(data.stylePlanReports);
        let stylePlanData  = JSON.parse(data.stylePlanFreeDay);

        this.MAX_TOTAL_COUNT = censusData.MAX_TOTAL_COUNT;

        for(let i in censusData){
            if(!censusData.hasOwnProperty(i)){ continue; }
            if(i === "MAX_TOTAL_COUNT") { continue; }
            censusData[i] = JSON.parse(censusData[i]);
            censusData[i].proStyleNoModelList = JSON.parse(censusData[i].proStyleNoModelList);
        }

        styleData = styleData || [];

        this.setState({data:censusData,transverseData:styleData,stylePlanData});
    };

    componentWillMount(){
        const state = this.props.location.state;

        if(!state){ message.error("请以正常方式进入页面"); return; }
        this.propState = state;

        // 第一次计算时间，并请求数据/
        const preDate = this.preDate._d;
        const endDate = new Date(preDate);

        endDate.setMonth(preDate.getMonth()+3);

        // 请求之前一定要有 this.propState(上页传递过来的班组id信息)
        this.httpRequest({startDate:dateFormat(preDate),endDate:dateFormat(endDate)},(data)=>{
            this.reDataformat(data);
            this.DatePickerChange(this.preDate); //更新计算时间数据
        })
    };

    // 计算Y轴刻度
    yAxisCalibration(maxValue){
        if(type(maxValue) === "string"){ maxValue = parseInt(maxValue); }
        const AVERAGE = maxValue/4;
        let Arr = [];
        maxValue+=AVERAGE;
        if(type(maxValue) === "number" && maxValue%AVERAGE === 0 ){
            while(1){
                if(Arr && Arr[Arr.length-1] <= 0){ break; }
                Arr.push(maxValue-=AVERAGE)
            }
        }
        return Arr;
    };

    // 日期change更改事件
    DatePickerChange = (date)=>{
        const max = 3; //间隔月数

        let d = new Date(date._d);
        let d_end = new Date(d);
        let dateArr = [];
        let yAxis = [];

        d_end.setMonth(d.getMonth()+max);

        // 更新时间数组取出90天中的时间列表
        while(1) {
            if (d.valueOf() > d_end.valueOf()) { break;}

            dateArr.push(dateFormat(d));  // dateArr :: ["2017-05-05","2017-05-06"......]

            d.setDate(d.getDate() + 1);  //  自增1天
        }

        if(this.MAX_TOTAL_COUNT){yAxis = this.yAxisCalibration(this.MAX_TOTAL_COUNT);}

        this.httpRequest({startDate:dateFormat(date._d),endDate:dateFormat(d_end)},this.reDataformat);

        this.setState({
            canvasWidth:dateArr.length * 40,
            date,  //当前选择的开始时间
            dateArr, //本地时间队列
            currentDate:dateFormat(d_end),  //结束显示的时间
            yAxis, //Y轴刻度数组
        },()=>{
            // 跟新滚动条居中
            const e = this.refs.yyd_chart;
            const scrollWdith = (e.scrollWidth - e.offsetWidth)/2;
            scrollMove(e,scrollWdith);
        });
    };

    render() {
        const {
            date,  //head上选择的时间
            currentDate,  //至多长时间【显示】
            dateArr,  //本地计算的时间列表
            data,  //竖向chart数据
            yAxis,  //横向Y轴刻度
            canvasWidth,  //两个画布的宽度
            transverseData,  //横向chart的数据
            stylePlanData,   // 横向chart数据bar
            proWorkGroup,  //班组数据
        } = this.state;

        const dateArrRender = ()=>
            dateArr.map((dayValueOf,_i)=>
                <BarNavUiComponent
                    key={`navBar-${_i}`}
                    index={_i}
                    isShaft={false}
                    date={dayValueOf}
                    isEmpty={stylePlanData[dayValueOf] === "0"}
                    MAX_TOTAL_COUNT={this.MAX_TOTAL_COUNT}
                />
        );

        return(<div className="scheduling">
                <Header
                    date={date}
                    DatePickerChange={this.DatePickerChange}
                    currentDate={currentDate}
                />

                <div className="scheduling_WorkshopHeader">
                    <div data-type="block">
                        {proWorkGroup.workShopName} {proWorkGroup.name}
                    </div>
                    <span>
                        工人数量 : {proWorkGroup.workerNum} 人
                    </span>
                </div>

                <div className="scheduling-chart">
                    <div className="Yyd-chart" ref="yyd_chart">
                        <Logic_chartTransverse
                            BarComRender={dateArrRender}
                            canvasWidth={canvasWidth}
                            data={transverseData}
                            canvasStartDate={date}
                        />

                        <Logic_chartVertical
                            data={data}  //data :: {"2017-05-12":xxx}
                            isSewing={true}  //是否展示于 Sewing 页面
                            canvasWidth={canvasWidth}  //canvasWidth :: number
                            dateArr={dateArr}   // ["2017-5-12"....]
                            MAX_TOTAL_COUNT={this.MAX_TOTAL_COUNT}
                        />

                    </div>

                    {/*竖轴*/}
                    <Logic_chartYaxis
                        yAxis={yAxis}
                    />
                </div>

                <View_describe />
            </div>
        )
    }
}